package com.xuhf.task;

import com.alibaba.fastjson.JSONObject;
import com.xuhf.conf.RabbitMQConf;
import com.xuhf.conf.RedisKeyConstant;
import com.xuhf.model.CollectMessage;
import com.xuhf.service.RabbitMQService;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class CollectorTask {

    @Autowired
    private RabbitMQService rabbitMQService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "*/5 * * * * *")
    public void collectToday() {
        CollectMessage collectMessage = new CollectMessage();
        int ran = new Random().nextInt(5) + 10;
        collectMessage.setMacid(String.valueOf(ran));
        String key = RedisKeyConstant.getGpsTodayLastTimeKey(String.valueOf(ran));
        String value = redisTemplate.opsForValue().get(key);
        DateTime end = new DateTime();
        collectMessage.setEndTime(end.toDate());
        collectMessage.setEndTimestamp(end.toDate().getTime());
        DateTime start = end.minusHours(1);
        if (StringUtils.isNotBlank(value)) {
            start = new DateTime(Long.parseLong(value));
        }
        collectMessage.setStartTime(start.toDate());
        collectMessage.setStartTimestamp(start.toDate().getTime());
        redisTemplate.opsForValue().set(key, String.valueOf(end.toDate().getTime()));
        rabbitMQService.send(RabbitMQConf.GPS_EXCHANGE, RabbitMQConf.GPS_TODAY_COLLECT_ROUTING, JSONObject.toJSONString(collectMessage));
    }

    @Scheduled(cron = "*/5 * * * * *")
    public void collectHistory() {
        CollectMessage collectMessage = new CollectMessage();
        int ran = new Random().nextInt(100) + 10;
        collectMessage.setMacid(String.valueOf(ran));
        collectMessage.setDay(new DateTime().toString("yyyy-MM-dd"));
        rabbitMQService.send(RabbitMQConf.GPS_EXCHANGE, RabbitMQConf.GPS_HISTORY_COLLECT_ROUTING, JSONObject.toJSONString(collectMessage));
    }
}
